# -*- coding:UTF-8 -*-
import re
import os, sys
import shutil
from template import template_path
import traceback


def get_first_dir(path):
    if not path:
        return ""
    dirs = re.split("[/|\\\\]*", path)
    if len(dirs) == 1:
        return path
    else:
        return dirs[0]


def make_file(file_path):
    if os.path.exists(file_path):
        return False
    if not file_path or len(file_path) == 0:
        return False
    suffix = os.path.splitext(file_path)[-1]
    if not suffix:
        os.makedirs(file_path, mode=0o755, exist_ok=True)
        return True
    else:
        # dir = os.path.dirname(file_path)
        # 解决pyinstaller打包python程序可执行文件路径问题
        if getattr(sys, 'frozen', False):  # 判断是exe还是.py程序
            dir = os.path.dirname(sys.executable)  # exe程序路径
        elif __file__:
            dir = os.path.dirname(__file__)  # .py程序路径
        if not os.path.exists(dir):
            os.makedirs(dir, mode=0o755, exist_ok=True)
        suffix = suffix[1:].lower()
        if suffix in ["text", "md", "markdown", "xlsx", "docx", "pptx"]:
            template = os.path.join(template_path, f"template.{suffix}")
            shutil.copy(template, file_path)
            # os.rename(os.path.join(dir, f"template.{suffix}"), file_path)
            return True
        return False


def delete_file(file_path, recursion=True):
    if not file_path or len(file_path) == 0:
        return False
    if os.path.exists(file_path):
        if os.path.isdir(file_path):
            if recursion:
                shutil.rmtree(file_path)
                return True
            else:
                os.rmdir(file_path)
                return True
        else:
            os.remove(file_path)
            return True
    return False


def copy(src:str, dst:str):
    """
    复制文件（或目录）到指定目录
    :param src: 原文件，需要复制的文件或目录
    :param dst: 目标文件夹
    :return:
    """
    if os.path.exists(src) and os.path.exists(dst) and os.path.isdir(dst):
        if os.path.isfile(src):
            shutil.copy(src, dst)
        else:
            dst = os.path.join(dst, os.path.split(src)[1])
            if not os.path.exists(dst):
                os.makedirs(dst, mode=0o755, exist_ok=True)
            files = os.listdir(src)
            for f in files:
                f = os.path.join(src, f)
                copy(f, dst)

if __name__ == '__main__':
    copy("C:\\Users\\zhang\\Desktop\\test\\a", "C:\\Users\\zhang\\Desktop\\test\\b")